package com.xin.di.uav.applet.login.controller;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.xin.di.uav.common.annotate.DistributedLock;
import com.xin.di.uav.common.annotate.ReSubmit;
import com.xin.di.uav.operate.service.LoginService;
import com.xin.di.uav.applet.utils.RandomUtils;
import com.xin.di.uav.common.utils.RedisKeyConstants;
import com.xin.di.uav.applet.utils.SendSmsUtils;
import com.xin.di.uav.common.enums.ServicePrefixEnum;
import com.xin.di.uav.common.exception.BusinessException;
import com.xin.di.uav.common.utils.RedisPrefixKey;
import com.xin.di.uav.common.utils.Rs;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.constraints.Size;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * @author LTQ
 * 登录
 */
@Api(tags = "登录")
@RestController
@RequestMapping("/home/")
@Validated
public class LoginController {


    @Autowired
    private LoginService loginService;

    @Autowired
    private RedisTemplate redisTemplate;


    @Operation(tags = "通过微信号登录", description = "通过微信号登录")
    @GetMapping(value = {"login-by-wechat"})
    public Rs<String> loginByWechat(@RequestParam("loginCode") String loginCode, @RequestParam("encryptedData") String encryptedData, @RequestParam("ikey") String iv) {
        String token = loginService.loginByWechat(loginCode, encryptedData, iv);
        return Rs.success(token);
    }

    @GetMapping("get-code")
    @Operation(tags = "获取验证码", description = "获取验证码")
    @ReSubmit(key = RedisKeyConstants.sendSms, expire = 3)
    @DistributedLock(key = RedisKeyConstants.sendSms, expireTime = 5, userDimension = true)
    public Rs<String> getCode(@RequestParam @Size(min = 11, max = 11) String phoneNumber) {
        phoneNumber = phoneNumber.trim();

        boolean is11Digits = Pattern.matches("\\d{11}", phoneNumber);
        if (!is11Digits) {
            return Rs.error("手机号格式不正确");
        }

        String code = RandomUtils.getStringRandom();
        // 构造API请求对象，请替换请求参数值
        SendSmsRequest sendSmsRequest = new SendSmsRequest().setPhoneNumbers(phoneNumber).setSignName("深圳市鑫地网络科技").setTemplateCode("SMS_314685591").setTemplateParam("{\"code\":\"" + code + "\"}"); // TemplateParam为序列化后的JSON字符串。

        SendSmsResponse sendSmsResponse = SendSmsUtils.sendSms(sendSmsRequest);
        if (sendSmsResponse.getStatusCode() != 200) {
            throw new BusinessException("验证码发送失败");

        } else {
            if (!sendSmsResponse.getBody().getCode().equals("OK")) {
                throw new BusinessException("验证码发送失败");
            }
        }
        redisTemplate.opsForValue().set(ServicePrefixEnum.RESCUE + RedisPrefixKey.APPLET_PHONE_CODE + phoneNumber, code);
        //需要五分钟内登录
        redisTemplate.expire(ServicePrefixEnum.RESCUE + RedisPrefixKey.APPLET_PHONE_CODE + phoneNumber, 5, TimeUnit.MINUTES);
        return Rs.success();
    }

    @GetMapping("login-by-code")
    public Rs<String> loginByCode(@RequestParam @Size(min = 11, max = 11) String phoneNumber, @RequestParam @Size(min = 6, max = 6) String code, @RequestParam String loginCode) {
//        if (!"test".equals(encryptConfigEnv)) {
//            String phoneCode = (String) redisTemplate.opsForValue().get(ServicePrefixEnum.RESCUE + RedisPrefixKey.APPLET_PHONE_CODE + phoneNumber);
//            if (!code.equals(phoneCode)) {
//                return Rs.failed("验证失败");
//            } else {
//                redisTemplate.delete(ServicePrefixEnum.RESCUE + RedisPrefixKey.APPLET_PHONE_CODE + phoneNumber);
//            }
//        }
        String token = loginService.loginByPhoneNumber(phoneNumber, loginCode);
        return Rs.success(token);
    }
}
